var form;
var index; //组织机构树弹出层的索引
var tableIns;
var tree;
var headimg;
var ctxPath = '/'
$(function () {
    layui.config({
        base: ctxPath + 'lib/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index'//主入口模块
    }).use(['index', 'table', 'tree', 'upload', 'form'], function () {
        var table = layui.table;
        form = layui.form;
        tree = layui.tree;
        var upload = layui.upload;
        // 渲染表格
        tableIns = table.render({
            elem: '#table',
            toolbar: '#table-title',
            url: 'cyuserPager',
            cols: [[
                {type: 'numbers'},
                {
                    field: 'cyqxh', title: '查验区名称', align: 'center', templet: function (d) {
                        var cyqmc = "";
                        $.ajax({
                            type: "GET",
                            data: {"cyqxh": d.cyqxh},
                            async: false,
                            url: ctxPath + "system/organization/name",
                            success: function (res) {
                                cyqmc = res.obj;
                            }
                        });
                        return cyqmc;
                    }
                },
                {field: 'cyyxm', title: '查验员姓名', align: 'center'},
                {field: 'cyysfzhm', title: '查验员身份证号码', align: 'center'},
                {
                    field: 'cyyzc', title: '查验员职称', align: 'center', templet: function (d) {
                        if (d.cyyzc == "1") {
                            return "初级查验员";
                        } else if (d.cyyzc == "2") {
                            return "中级查验员";
                        } else if (d.cyyzc == "3") {
                            return "高级查验员";
                        } else {
                            return "未知";
                        }
                    }
                },
                {field: 'right', title: '操作', toolbar: '#table-toolbar', align: 'center'},
            ]],
            where: {
                cyqxh: $("#cyqxhSearch").val(),
                cyyxm: $("#usernameSearch").val(),
                jybh: $("#jybhSearch").val()
            },
            page: true,
            request: {
                pageName: 'page', //页码的参数名称，默认：page
                limitName: 'limit' //每页数据量的参数名，默认：limit
            }
        });
        initOrganSelect()
        //监听行工具事件
        table.on('tool(table)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                openEdit(data)
            } else if (obj.event === 'del') {
                openDel(data);
            }
        });
        //监听提交
        form.on('submit(searchSubmit)', function () {
            tableIns.reload({  
                where: {
                    cyqxh: $("#cyqxhSearch").val(),
                    cyyxm: $("#usernameSearch").val(),
                    jybh: $("#jybhSearch").val()
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            return false;

        });
        form.on('submit(submitUser)', function (data) {
            cyuserSubmit($("#oper").val())
        })
        //执行实例
        var uploadInst = upload.render({
            elem: '#test1' //绑定元素
            , url: ctxPath + 'system/cyuser/headImgInfo'
            , method: 'POST'
            , auto: false
            , acceptMime: 'image/jpg,image/png'
            , choose: function (obj) {
                //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
                obj.preview(function (index, file, result) {
                    if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(file.name)) {
                        return layer.alert("图片类型必须是.jpeg,jpg,png中的一种");
                    }
                    // else if (file.size > 500 * 1024) {
                    //     return layer.alert("文件太大！请上传不超过500k的图片");
                    // }
                    else {
                        result = result.replace(/\r|\n/g, '').replace('data:image/jpg;base64,', '').replace('data:image/png;base64,', '').replace('data:image/jpeg;base64,', '');
                        headimg = result;
                    }
                });
            }
        });
    });
});

function openEdit(data) {
    layer.open({
        type: 1,
        title: "编辑查验员信息",
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['50%', '70%'],
        content: $('#cyuserEdit'),

        success: function () {
            $.get(ctxPath + "system/organization/name", {"cyqxh": data.cyqxh}, function (res) {
                $("#cyqmc").val(res.obj)
            });
            $("#headimg").attr("src", "data:image/png;base64," + data.headimg);
            //填充表单
            form.val('cyuserForm', data);
            $("#oper").val("1")
            renderForm()

        }, end: function () {
            cleanForm("cyuserForm")
        }
    });
}

function openAdd() {
    layer.open({
            type: 1,
            title: "新建执法记录仪信息",
            fixed: false,
            resize: false,
            shadeClose: true,
            area: ['50%', '70%'],
            content: $('#cyuserEdit'),

            success: function () {
                $("#oper").val("0")
                renderForm()
            },
            end: function () {
                cleanForm("cyuserForm")
            }
        }
    )
}

function cyuserSubmit(oper) {
    var type = oper == "0" ? "POST" : "PUT";
    var cyuser = serializeObject($("#cyuserForm"));
    cyuser.headImg_base64 = headimg
    $.ajax({
        type: type,
        data: cyuser,
        url: ctxPath + "system/cyuser/cyuserInfo"
    });
}
function submitCancel() {
 layer.closeAll()
}
/**
 * 删除配置
 * @param obj
 */
function openDel(obj) {
    layer.confirm('您确定要删除查验员：' + obj.cyyxm + '么', function () {
        $.ajax({
            type: "DELETE",
            data: {
                "id": obj.id
            },
            url: ctxPath + "system/cyuser/cyuserInfo",
            complete: function () {
                tableReload()
            }
        });
    });
}

function tableReload() {
    tableIns.reload({
        page: {
            curr: 1 //重新从第 1 页开始
        }
    });
}

/**
 * 构建组织机构树
 */
function buildOrganTree() {
    $.ajax({
        type: "GET",
        url: ctxPath + "system/organization/treeInfo",
        data:{"islimit" : 1},  // islimit = 1 限制用户查看查验机构
        success: function (result) {
            if (result.code == "1") {
                var data = result.obj
                tree.render({
                    elem: '#organTree',  //绑定元素
                    data: data,
                    id: 'treeId',
                    onlyIconControl: true, //设置仅选中节点图标时才会伸缩
                    click: function (obj) {
                        $("#cyqxh").val(obj.data.id);
                        $("#cyqmc").val(obj.data.title);  //将选中的机构名回显到表单
                        layer.close(index)  //关闭组织机构弹出层
                    }
                });
            } else {
                layer.alert(result.msg)
            }
        }
    });
}

/**
 * 打开组织机构树弹出层
 */
function openOrganTree() {
    index = layer.open({
        type: 1,
        title: "选择机构",
        fixed: false,
        resize: false,
        shadeClose: true,
        area: ['20%', '60%'],
        content: $('#organDiv'),
        success: function () {
            buildOrganTree();  //构建组织机构树
        }
    });
}

function initOrganSelect() {
    $.ajax({
        type: "GET",
        url: ctxPath + "system/organization/organList",
        data:{"islimit" : 1},  // islimit = 1 限制用户查看查验机构
        success: function (res) {
            var data = res.obj;
            for (var i = 0; i < data.length; i++) {
                $("#cyqxhSearch").append("<option value='" + data[i].cyqxh + "'>" + data[i].name + "</option>")
            }
            renderForm();
        }
    });
}